﻿Imports System.IO
Imports System.Data.SqlClient
Imports System.Drawing.Printing
Public Class frmModuloDieselFinal
    'variables scanner tarjetas
    Inherits System.Windows.Forms.Form
    Dim result As Integer
    Dim handle_Renamed As Integer
    Dim deviceType As Integer
    Dim userID As Integer

    'variables scanner huellas
    Private m_ScannerManager As UFScannerManager
    Private m_Scanner As UFScanner
    Private m_Matcher As UFMatcher
    Private m_Database As UFDatabase
    Private m_strError As String
    Private m_Serial As Integer
    Private m_UserID As String
    Private m_FingerIndex As Integer
    Private m_Template1 As Byte()
    Private m_Template1Size As Integer
    Private m_Template2 As Byte()
    Private m_Template2Size As Integer
    Private m_Memo As String
    '
    Private Const MAX_USERID_SIZE As Integer = 50
    Private Const MAX_TEMPLATE_SIZE As Integer = 1024
    Private Const MAX_MEMO_SIZE As Integer = 100
    '
    Private Const DATABASE_COL_SERIAL As Integer = 0
    Private Const DATABASE_COL_USERID As Integer = 1
    Private Const DATABASE_COL_FINGERINDEX As Integer = 2
    Private Const DATABASE_COL_TEMPLATE1 As Integer = 3
    Private Const DATABASE_COL_TEMPLATE2 As Integer = 4
    Private Const DATABASE_COL_MEMO As Integer = 5


    'variables generales

    Dim FalloalAbrir As Boolean = False
    Private minuto As Integer = 0
    Private segundo As Integer = 0
    Private milisegundo As Integer = 0
    Private minutoM As Integer = 0
    Private segundoM As Integer = 0
    Private milisegundoM As Integer = 0
    Dim Bitacora As New clsActividad
    Dim Usuario As New clsUsuarioPrincipal
    Dim IntentosHuella As Integer

    'variables dispensario diesel
    Dim x As Short
    Dim i As Short
    Dim Resp As Short
    Dim Datos(9) As String
    Dim Dispensarios As String
    Public VelTrans(1) As Integer

    Dim Diesel As New clsDiesel

    Private prtSettingsBoletos As PrinterSettings
    Private prtDoc1Boletos As PrintDocument
    Private prtDoc2Boletos As PrintDocument
    Private prtDoc3Boletos As PrintDocument
    Private prtFontBoletos As System.Drawing.Font
    Private lineaActualBoletos As Integer

    Private Sub frmModuloDieselFinal_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        If FalloalAbrir = True Then
            BS_CloseSocket(handle_Renamed)
            Bitacora.RegistraActividad("Cerró al Módulo de Diesel")
            Usuario.Ubicacion("Ventana Principal")
        Else
            BS_CloseSocket(handle_Renamed)
            Bitacora.RegistraActividad("Cerró al Módulo de Diesel")
            Usuario.Ubicacion("Ventana Principal")

            Terminar()

            Bitacora.RegistraActividad("Cerró al Módulo de Diesel")
            Usuario.Ubicacion("Ventana Principal")

        End If


        i = Bloquear(1)
        If i = 0 Then
            'sgBox("El bloqueo Se Realizó Con Exito", MsgBoxStyle.OkOnly, "información")
        Else
            'sgBox("No se bloque", MsgBoxStyle.OkOnly, "información")
        End If



    End Sub


    Private Sub frmModuloDieselFinal_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ToolStrip1.Cursor = Cursors.Hand
        ToolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System

        pbTicket.BackgroundImage = Image.FromFile(Application.StartupPath & "\Check1.png")
        chTicket.Checked = True
        lblTicket.Text = "Ticket"

        If UsuarioActivo = "ADMINISTRADOR" Then
            btnScanner.Visible = True
        Else
            btnScanner.Visible = False
        End If

        btnIniciar_2.Enabled = False

        Dim IPSCANNER As String = LeerDatosIniciales()
        Dim Scanner As Boolean = IniciaLector(IPSCANNER)

        If Scanner = True Then
            MsgBox("Debe verificar la conexión del lector de tarjetas y reiniciar el sistema para poder continuar", MsgBoxStyle.Critical, "Aviso")
            txtStatus.ForeColor = Color.Red
            txtStatus.Text = "VERIFÍQUE CONEXION CON SCANNER RFID"
        Else
            timerLector.Enabled = True
        End If

        If FalloalAbrir = False Then
            'IniciaDispensario()
            'If LeerEstatus(1) = 0 Then
            i = Desbloquear(1)
            btnIniciar_2.Enabled = True
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
            'Else
            'MsgBox("El dispensario no está disponible", MsgBoxStyle.Critical, "información")
            'txtStatus.ForeColor = Color.Red
            'txtStatus.Text = "VERIFÍQUE CONEXION EL DISPENSARIO"
            'End If

        Else
            txtStatus.ForeColor = Color.Red
            txtStatus.Text = "VERIFÍQUE CONEXION CON SCANNER BIOMETRICO"
        End If



        TextBox1.Select()
        TextBox1.Focus()

    End Sub
    Sub IniciaDispensario()
        VelTrans(0) = 19200
        VelTrans(1) = 19200
        T2000 = New TEAM.SerialTXRX.SerialDeviceProtocols(VelTrans, 19200)
        Dim TanqueSPLIT As String = File.ReadAllText(Application.StartupPath & "\INICIAL.txt")
        Dim Cadena As String() = TanqueSPLIT.Split("|")
        Dim PuertoCom As String = Cadena(1)
        T2000.Connect(PuertoCom)
    End Sub
    Function LeerDatosIniciales() As String

        Dim TanqueSPLIT As String = File.ReadAllText(Application.StartupPath & "\INICIAL.txt")
        Dim Cadena As String() = TanqueSPLIT.Split("|")
        Dim Tanque As String = Cadena(0)

        Dim IdTanque As Integer = BuscarIntDatoCitra("SELECT IdTanque FROM Tanques WHERE Nombre='" & Tanque & "'")
        Dim CuentaLitros As Double = BuscarDblDatoCitra("SELECT Cuentalitros FROM Tanques WHERE IdTanque=" & IdTanque)
        Dim LitrosExistentes As Double = BuscarDblDatoCitra("SELECT LtsAproximados FROM Tanques WHERE IdTanque=" & IdTanque)
        Dim LitrosSurtidos As Double = BuscarDblDatoCitra("SELECT  SUM(LITROS) AS LITROS FROM DieselTemp WHERE IdTanque=" & IdTanque)

        Dim PrecioDiesel As Double  'DE DONDE SACAR PRECIO DIESEL?"
        txtPrecio.Text = Format(12.5, "N2")

        txtTanque.Text = Tanque
        txtCuentalitros.Text = CuentaLitros
        txtLtsDisponibles.Text = LitrosExistentes
        txtSurtidos.Text = LitrosSurtidos
        Application.DoEvents()

        Dim IP As String = BuscarStrDatoCitra("SELECT IP_SCANNER FROM TANQUES WHERE IDTANQUE=" & IdTanque)

        Return IP

    End Function
    Function IniciaLector(ByVal DireccionIp As String) As Boolean

        'ESTO ES EL SDK DEL LECTOR DE TARJETAS
        result = BS_InitSDK()
        userID = 0

        Dim deviceID As Object
        result = BS_OpenSocket(DireccionIp, 1471, handle_Renamed)

        '//////////////////////////////////////////////
        'Dim wiegandConfig As BSWiegandConfig
        'result = BS_ReadWiegandConfig(handle_Renamed, wiegandConfig)
        'If result <> 0 Then
        'tbxMessage.AppendText("No se pudo abrir el canal de comunicación " & IP & vbNewLine)
        'FalloalAbrir = True
        'Exit Sub
        'End If
        '        wiegandConfig.Initialize()
        '//////////////////////////////////////////////

        If result <> 0 Then
            MsgBox("No se pudo abrir el canal de comunicación: " & DireccionIp, MsgBoxStyle.Critical, "Aviso")
            FalloalAbrir = True
            Return FalloalAbrir
            Exit Function
        End If

        result = BS_GetDeviceID(handle_Renamed, deviceID, deviceType)
        If result <> 0 Then
            MsgBox("No se pudo obtener el ID del dispositivo", MsgBoxStyle.Critical, "Aviso")
            FalloalAbrir = True
            Return FalloalAbrir
            Exit Function
        End If

        result = BS_SetDeviceID(handle_Renamed, deviceID, deviceType)

        If result <> 0 Then
            MsgBox("No se pudo asignar el ID del dispositivo", MsgBoxStyle.Critical, "Aviso")
            FalloalAbrir = True
            Return FalloalAbrir
            Exit Function
        End If

        FalloalAbrir = False

        Return FalloalAbrir


    End Function

    Private Sub ToolStripButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnScanner.Click
        frmIPScanner.ShowDialog()
    End Sub



    Private Sub timerLector_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerLector.Tick
        segundo = 0
        milisegundo += 1
        If milisegundo = 9 Then
            milisegundo = 0
            segundo += 1

            If segundo = 1 Then
                IniciaScanner()
                timerLector.Enabled = False
            End If
        End If
    End Sub
    Sub IniciaScanner()
        'ESTO ES EL SDK DEL LECTOR DE HUELLAS
        FalloalAbrir = False

        m_ScannerManager = New UFScannerManager(Me)
        m_Scanner = Nothing
        m_Matcher = Nothing
        m_Database = Nothing

        m_Template1 = New Byte(MAX_TEMPLATE_SIZE) {}
        m_Template2 = New Byte(MAX_TEMPLATE_SIZE) {}
        '==========================================================================='
        ' Initilize scanners
        '==========================================================================='
        Dim ufs_res As UFS_STATUS
        Dim nScannerNumber As Integer

        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufs_res = m_ScannerManager.Init()
        Windows.Forms.Cursor.Current = Me.Cursor
        If (ufs_res = UFS_STATUS.OK) Then
            'tbxMessage.AppendText("Conexión del scanner: Correcta" & vbNewLine)
        Else
            UFScanner.GetErrorString(ufs_res, m_strError)
            MsgBox("Conexión del scanner: " & m_strError, MsgBoxStyle.Critical, "Aviso")
            FalloalAbrir = True
            Exit Sub
        End If

        nScannerNumber = m_ScannerManager.Scanners.Count
        'tbxMessage.AppendText("UFScanner GetScannerNumber: " & nScannerNumber & vbNewLine)

        If (nScannerNumber = 0) Then
            MsgBox("No hay scanners disponibles", MsgBoxStyle.Critical, "Aviso")
            FalloalAbrir = True
            Exit Sub
        End If

        m_Scanner = m_ScannerManager.Scanners(0)
        '==========================================================================='

        '==========================================================================='
        ' Open database
        '==========================================================================='
        Dim ufd_res As UFD_STATUS

        m_Database = New UFDatabase()

        ' Generate connection string
        Dim Connection As String

        Connection = BiometriaConnectionOperadores

        ' Open database
        ufd_res = m_Database.Open(Connection, "", "")
        If (ufd_res = UFD_STATUS.OK) Then
            'tbxMessage.AppendText("Apertura de la base de datos: Correcta" & vbNewLine)
        Else
            UFDatabase.GetErrorString(ufd_res, m_strError)
            MsgBox("Apertura de la base de datos: " & m_strError, MsgBoxStyle.Critical, "Aviso")
            FalloalAbrir = True
            Exit Sub
        End If

        ' Create matcher
        '==========================================================================='
        m_Matcher = New UFMatcher()
        '==========================================================================='
    End Sub
    Sub Terminar()
        '==========================================================================='
        ' Uninit scanner module
        '==========================================================================='
        Dim ufs_res As UFS_STATUS

        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufs_res = m_ScannerManager.Uninit()
        Windows.Forms.Cursor.Current = Me.Cursor

        If (ufs_res = UFS_STATUS.OK) Then
            ' tbxMessage.AppendText("UFScanner Uninit: OK" & vbNewLine)
        Else
            UFScanner.GetErrorString(ufs_res, m_strError)
            'tbxMessage.AppendText("UFScanner Uninit: " & m_strError & vbNewLine)
        End If

        '==========================================================================='

        '==========================================================================='
        ' Close database
        '==========================================================================='

        If (Not Equals(m_Database, Nothing)) Then
            Dim ufd_res As UFD_STATUS

            ' Close database
            ufd_res = m_Database.Close()
            If (ufd_res = UFD_STATUS.OK) Then
                'tbxMessage.AppendText("UFDatabase Close: OK" & vbNewLine)
            Else
                UFDatabase.GetErrorString(ufd_res, m_strError)
                'tbxMessage.AppendText("UFDatabase Close: " & m_strError & vbNewLine)
            End If
        End If

    End Sub
    Sub LeerRFID(ByVal IdTanque As Integer)
        btnSalir.Enabled = False

        TextBox1.Select()
        TextBox1.Focus()

        Dim CardID As Integer
        Dim CustomID As Integer

        result = BS_ReadCardIDEx(handle_Renamed, CardID, CustomID)


        '//////////////////////////////////////////////////////////////
        'result=BS_ReadConfig(handle_Renamed,beplus

        'Exit Sub

        '////////////////////////////////////////////////////////////////////////
        txtStatus.ForeColor = Color.Green
        txtStatus.Text = "BUSCANDO AUTOBUS"
        TextBox1.Select()
        TextBox1.Focus()


        If result <> 0 Then
            MsgBox("No se encontro ningún autobus", MsgBoxStyle.Information, "Aviso")
            btnIniciar_2.Enabled = True
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
            btnSalir.Enabled = True
            TextBox1.Select()
            TextBox1.Focus()
            Exit Sub
        End If

        Dim CodigoTarjeta As String = CardID
        Dim IdAutobus As Integer = BuscarIntDatoCitra("SELECT IdAutobus FROM Autobuses WHERE Texto04='" & CodigoTarjeta & "'")
        If IdAutobus > 0 Then
            'VERIFICA NO SEA BAJA
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "VERIFICANDO STATUS DEL AUTOBUS"
            TextBox1.Select()
            TextBox1.Focus()

            Dim Status As Integer = BuscarIntDatoCitra("SELECT Estatus FROM Autobuses WHERE IdAutobus=" & IdAutobus)
            If Status = 0 Then
                MsgBox("El autobus identificado esta dado de baja", MsgBoxStyle.Exclamation, "Aviso")
                txtStatus.ForeColor = Color.Green
                txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
                btnIniciar_2.Enabled = True
                btnSalir.Enabled = True
                TextBox1.Select()
                TextBox1.Focus()
                Exit Sub
            Else
                'AQUI SE VERIFICA SI YA CUMPLIO LAS HORAS NECESARIAS PARA VOVER A CARGAR COMBUSTIBLE
                Dim IdRuta As Integer = BuscarIntDatoCitra("SELECT IdRuta FROM Autobuses WHERE IdAutobus=" & IdAutobus)
                Dim HorasCarga As Integer = BuscarIntDatoCitra("SELECT Importe01 FROM Rutas WHERE IdRuta=" & IdRuta)
                Dim FechaStr As String = BuscarStrDatoCitra("SELECT Texto05 FROM AUTOBUSES WHERE IDAUTOBUS=" & IdAutobus)

                If FechaStr = "" Then
                    txtAutobus.Text = BuscarStrDatoCitra("SELECT NoEconomico FROM Autobuses WHERE IdAutobus=" & IdAutobus)
                    Application.DoEvents()
                    txtStatus.ForeColor = Color.Green
                    txtStatus.Text = "BUSCANDO ÓRDEN DE ABASTO DE DIESEL"
                    TextBox1.Select()
                    TextBox1.Focus()
                    Application.DoEvents()
                    BuscarOrden(IdAutobus, IdTanque)
                    Application.DoEvents()
                    Exit Sub
                End If

                Dim UltimaCarga As Date = CDate(FechaStr)
                Dim HoraActual As Date = Now()
                Dim HorasTranscurridas As Integer = DateDiff(DateInterval.Hour, UltimaCarga, HoraActual)

                If HorasTranscurridas >= HorasCarga Then
                    txtAutobus.Text = BuscarStrDatoCitra("SELECT NoEconomico FROM Autobuses WHERE IdAutobus=" & IdAutobus)
                    Application.DoEvents()
                    txtStatus.ForeColor = Color.Green
                    txtStatus.Text = "BUSCANDO ÓRDEN DE ABASTO DE DIESEL"
                    TextBox1.Select()
                    TextBox1.Focus()
                    Application.DoEvents()
                    BuscarOrden(IdAutobus, IdTanque)
                    Application.DoEvents()
                Else
                    MsgBox("El autobus no cumple con el minimo de horas transcurridas para volver a abastecer (" & HorasTranscurridas & " horas desde ultimo abasto)", MsgBoxStyle.Critical, "Aviso")
                    txtStatus.ForeColor = Color.Green
                    txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
                    btnIniciar_2.Enabled = True
                    btnSalir.Enabled = True
                    TextBox1.Select()
                    TextBox1.Focus()
                    Exit Sub
                End If



            End If
        Else
            MsgBox("Se identificó un TAG RFID inválido", MsgBoxStyle.Critical, "Aviso")
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
            btnIniciar_2.Enabled = True
            btnSalir.Enabled = True
            TextBox1.Select()
            TextBox1.Focus()
            Exit Sub
        End If
    End Sub
    Sub BuscarOrden(ByVal IdAutobus As Integer, ByVal IdTanque As Integer)
        Dim IdOrden As Integer = BuscarIntDatoCitra("SELECT IdOrden FROM OrdenDiesel WHERE IdAutobus=" & IdAutobus & " AND Status='P' OR STATUS='R'")
        If IdOrden = 0 Then
            MsgBox("El autobús no tiene ninguna orden de diesel", MsgBoxStyle.Information, "Aviso")
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
            btnSalir.Enabled = True
            btnIniciar_2.Enabled = True
            txtAutobus.Clear()
            TextBox1.Select()
            TextBox1.Focus()
            Exit Sub
        Else
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "PROCESANDO DATOS DE ÓRDEN"
            TextBox1.Select()
            TextBox1.Focus()
            Application.DoEvents()

            Dim IdRuta As Integer = BuscarIntDatoCitra("SELECT IdRuta FROM OrdenDiesel WHERE IdOrden=" & IdOrden)
            Dim IdOperador As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM OrdenDiesel WHERE IdOrden=" & IdOrden)

            txtRuta.Text = BuscarStrDatoCitra("SELECT Nombre FROM Rutas where IDRUTA=" & IdRuta)
            txtOperador.Text = BuscarStrDatoCitra("SELECT NOMBRE FROM OPERADORESGLOBAL WHERE IDOPERADOR=" & IdOperador)
            TextBox1.Select()
            TextBox1.Focus()
            Application.DoEvents()
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "POR FAVOR COLOQUE SU DEDO ÍNDICE EN EL SCANNER"
            TextBox1.Select()
            TextBox1.Focus()
            Application.DoEvents()
            IntentosHuella = 1
            VerificaHuella(IdOperador, IdAutobus, IdOrden, IdTanque)

        End If

    End Sub
    Sub VerificaHuella(ByVal IdOperador As Integer, ByVal IdAutobus As Integer, ByVal IdOrden As Integer, ByVal IdTanque As Integer)
        Dim ufd_res As UFD_STATUS
        Dim ufm_res As UFM_STATUS
        ' Input finger data
        Dim Template As Byte() = New Byte(MAX_TEMPLATE_SIZE) {}
        Dim TemplateSize As Integer
        ' DB data
        Dim DBTemplate As Byte()() = Nothing
        Dim DBTemplateSize As Integer() = Nothing
        Dim DBSerial As Integer() = Nothing
        Dim DBTemplateNum As Integer
        '
        Dim MatchIndex As Integer




        ufd_res = m_Database.GetTemplateListWithSerial(DBTemplate, DBTemplateSize, DBTemplateNum, DBSerial)


        If (ufd_res <> UFD_STATUS.OK) Then
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "VERIFICANDO HUELLA DACTILAR"
            TextBox1.Select()
            TextBox1.Focus()
            Application.DoEvents()

            UFDatabase.GetErrorString(ufd_res, m_strError)
            MsgBox("No se pudieron leer las huellas de la base de datos", MsgBoxStyle.Critical, "Aviso")
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
            btnSalir.Enabled = True
            btnIniciar_2.Enabled = True
            txtAutobus.Clear()
            txtOperador.Clear()
            txtRuta.Clear()
            TextBox1.Select()
            TextBox1.Focus()
            Application.DoEvents()
            Exit Sub
        End If

        If (Not ExtractTemplate(Template, TemplateSize)) Then
            Exit Sub
        End If

        DrawCapturedImage(m_Scanner)
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufm_res = m_Matcher.Identify(Template, TemplateSize, DBTemplate, DBTemplateSize, DBTemplateNum, 5000, MatchIndex)
        Windows.Forms.Cursor.Current = Me.Cursor
        If (ufm_res <> UFM_STATUS.OK) Then
            UFMatcher.GetErrorString(ufm_res, m_strError)
            MsgBox("No se pudo identificar: " & m_strError, MsgBoxStyle.Critical, "Aviso")
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
            btnSalir.Enabled = True
            btnIniciar_2.Enabled = True
            txtAutobus.Clear()
            txtOperador.Clear()
            txtRuta.Clear()
            TextBox1.Select()
            TextBox1.Focus()
            Application.DoEvents()
            Exit Sub
        End If

        If (MatchIndex <> -1) Then
            'tbxMessage.AppendText("Identification succeed (Serial = " & DBSerial(MatchIndex) & ")" & vbNewLine)
            Dim CodigoOperador As String = BuscarStrDatoBiometriaOperadores("SELECT UserID FROM fingerprints WHERE Serial=" & DBSerial(MatchIndex))
            Dim IdOperadorHuella As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM OperadoresGlobal WHERE Codigo='" & CodigoOperador & "'")

            Dim Status As String = BuscarStrDatoCitra("SELECT EstadoEmpleado FROM OperadoresGlobal WHERE IdOperador=" & IdOperadorHuella)
            If Status = "B" Then
                MsgBox("El operador fué dado de baja", MsgBoxStyle.Critical, "Aviso")
                txtStatus.ForeColor = Color.Green
                txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
                btnSalir.Enabled = True
                btnIniciar_2.Enabled = True
                txtAutobus.Clear()
                txtOperador.Clear()
                txtRuta.Clear()
                TextBox1.Select()
                TextBox1.Focus()
                Application.DoEvents()
                Exit Sub
            End If

            If IdOperador = IdOperadorHuella Then

                'TRAE DATOS DE LITROS
                Dim LitroOrden As Double = BuscarDblDatoCitra("SELECT LstOrden FROM OrdenDiesel WHERE IdOrden=" & IdOrden)
                If LitroOrden = 500 Then
                    txtLitros.Text = "LLENO"
                Else
                    txtLitros.Text = LitroOrden
                End If

                txtLtsReales.Text = 0
                txtStatus.ForeColor = Color.Green
                txtStatus.Text = "POR FAVOR COLOQUE LA PISTOLA EN EL TANQUE DEL AUTOBÚS"
                TextBox1.Select()
                TextBox1.Focus()
                Application.DoEvents()
                Dim StatusCarga As New clsStatusCargaDiesel
                StatusCarga.IdTanque = IdTanque
                StatusCarga.IdAutobus = IdAutobus
                StatusCarga.Insertar()

                'MANDA SEÑAL DE APERTURA DE LA PUERTA
                'COMIENZA SINCRONIZACION DE BLUETOOTH CON PISTOLA
                'COMIENZA DESPACHO DE DIESEL

                i = Desbloquear(1)

                lblVta.Text = VentaLitros(1).ToString
                i = PrefijarLitros(1, CDbl(LitroOrden))
                Timer1.Enabled = True
                txtLtsReales.Text = "x"

        Else
            If IntentosHuella = 3 Then
                    MsgBox("El operador no corresponde con el indicado en la órden de abasto despues de 3 intentos", MsgBoxStyle.Critical, "Aviso")
                    Dim Hora As DateTime = Now()
                    Call SetSqlCitra("UPDATE ORDENDIESEL SET STATUS='R', OBSERVACIONES='EL OPERADOR NO ES EL INDICADO', FECHASURTIDO=" & Hora & " WHERE IDORDEN=" & IdOrden)

                    txtStatus.ForeColor = Color.Green
                    txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
                    btnSalir.Enabled = True
                    btnIniciar_2.Enabled = True
                    txtAutobus.Clear()
                    txtOperador.Clear()
                    txtRuta.Clear()
                    TextBox1.Select()
                    TextBox1.Focus()
                    Application.DoEvents()
                    Exit Sub
            Else
                IntentosHuella = IntentosHuella + 1
                Dim Resp As Integer = 0
                Resp = MsgBox("El operador no corresponde con el indicado en la órden de abasto ¿Desea reintentar?", MsgBoxStyle.YesNo, "Aviso")
                If Resp = 6 Then

                    txtStatus.ForeColor = Color.Red
                    txtStatus.Text = "REINTENTANDO VERIFICACIÓN DE HUELLA DACTILAR"
                    TextBox1.Select()
                    TextBox1.Focus()
                    Application.DoEvents()
                    VerificaHuella(IdOperador, IdAutobus, IdOrden, IdTanque)
                Else
                    txtStatus.ForeColor = Color.Green
                    txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
                    btnSalir.Enabled = True
                        btnIniciar_2.Enabled = True
                    txtAutobus.Clear()
                    txtOperador.Clear()
                    txtRuta.Clear()
                    TextBox1.Select()
                    TextBox1.Focus()
                    Application.DoEvents()
                    Exit Sub
                End If
            End If


        End If
        Else
            MsgBox("La huella indicada, no ha sido registrada", MsgBoxStyle.Information, "Aviso")
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
            btnSalir.Enabled = True
            btnIniciar_2.Enabled = True
            txtAutobus.Clear()
            txtOperador.Clear()
            txtRuta.Clear()
            TextBox1.Select()
            TextBox1.Focus()
            Application.DoEvents()
            Exit Sub
        End If
    End Sub
    Private Function ExtractTemplate(ByRef Template As Byte(), ByRef TemplateSize As Integer) As Boolean
        Dim ufs_res As UFS_STATUS
        Dim EnrollQuality As Integer

        m_Scanner.ClearCaptureImageBuffer()

        TemplateSize = 0
        Do
            ufs_res = m_Scanner.CaptureSingleImage()
            If (ufs_res <> UFS_STATUS.OK) Then
                UFScanner.GetErrorString(ufs_res, m_strError)
                MsgBox("Capturando imágen: " & m_strError, MsgBoxStyle.Information, "Aviso")
                txtStatus.ForeColor = Color.Green
                txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
                btnSalir.Enabled = True
                btnIniciar_2.Enabled = True
                txtAutobus.Clear()
                txtOperador.Clear()
                txtRuta.Clear()
                TextBox1.Select()
                TextBox1.Focus()
                Application.DoEvents()
                ExtractTemplate = False
                Exit Function
            End If

            DrawCapturedImage(m_Scanner)

            ufs_res = m_Scanner.Extract(Template, TemplateSize, EnrollQuality)
            If (ufs_res = UFS_STATUS.OK) Then
                'tbxMessage.AppendText("Extracción de imagen: OK" & vbNewLine)
                Exit Do
            Else
                UFScanner.GetErrorString(ufs_res, m_strError)
                MsgBox("Extracción de imagen: " & m_strError, MsgBoxStyle.Information, "Aviso")
                txtStatus.ForeColor = Color.Green
                txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
                btnSalir.Enabled = True
                btnIniciar_2.Enabled = True
                txtAutobus.Clear()
                txtOperador.Clear()
                txtRuta.Clear()
                TextBox1.Select()
                TextBox1.Focus()
                Application.DoEvents()
            End If
        Loop

        ExtractTemplate = True
    End Function
    Private Sub DrawCapturedImage(ByRef Scanner As UFScanner)
        Dim g As Graphics = pbImageFrame.CreateGraphics()
        Dim rect As Rectangle = New Rectangle(0, 0, pbImageFrame.Width, pbImageFrame.Height)
        Dim Resolution As Integer
        Try
            '
            'Scanner.DrawCaptureImageBuffer(g, rect, cbDetectCore.Checked);
            '
            Dim bitmap As Bitmap = Nothing
            Scanner.GetCaptureImageBuffer(bitmap, Resolution)
            pbImageFrame.Image = bitmap
        Finally
            g.Dispose()
        End Try
    End Sub
   

    Private Sub btnSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSalir.Click
        Close()

    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        'Dim Precio As Double
        'Dim TVenta As Double
        'Dim LecturaVenta As Double
        'LecturaVenta = VentaLitros(1)
        'If Val(txtLtsReales.Text) = LecturaVenta And LecturaVenta > 0 And lblVta.Text = "00" Then
        'TVenta = Val(txtLtsReales.Text)
        'Precio = LeerPrecio(1)
        'While Precio < 0
        'Precio = LeerPrecio(1)
        'End While
        'Timer1.Enabled = False

        'BUSCA KILOMETROS OPTOCONTROL
        'txtStatus.ForeColor = Color.Green
        'txtStatus.Text = "POR FAVOR, RETIRE LA PISTOLA DEL TANQUE"
        'TextBox1.Select()
        'TextBox1.Focus()
        'Application.DoEvents()
        'KilometrosOptocontrol()
        'txtStatus.ForeColor = Color.Green
        'txtStatus.Text = "POR FAVOR COLOQUE SU DEDO ÍNDICE EN EL SCANNER"
        'TextBox1.Select()
        'TextBox1.Focus()
        'Application.DoEvents()

        'IntentosHuella = 1
        'VerificaHuellaGuardado()
        'Else
        'If Math.Abs(Val(lblVta.Text)) <> Math.Abs(LecturaVenta) And Trim(Str(LecturaVenta)) <> "-1" Then
        'txtLtsReales.Text = Str(LecturaVenta)
        'GereraTotal()
        'lblVta.Text = "00"
        'End If
        'End If

        'temporal
        'BUSCA KILOMETROS OPTOCONTROL
        Timer1.Enabled = False
        txtLtsReales.Text = "150"
        GereraTotal()
        txtStatus.ForeColor = Color.Green
        txtStatus.Text = "POR FAVOR, RETIRE LA PISTOLA DEL TANQUE"
        TextBox1.Select()
        TextBox1.Focus()
        Application.DoEvents()
        KilometrosOptocontrol()
        txtStatus.ForeColor = Color.Green
        txtStatus.Text = "POR FAVOR COLOQUE SU DEDO ÍNDICE EN EL SCANNER"
        TextBox1.Select()
        TextBox1.Focus()
        Application.DoEvents()



        'IntentosHuella = 1
        VerificaHuellaGuardado()
    End Sub
    Sub VerificaHuellaGuardado()

        Dim ufd_res As UFD_STATUS
        Dim ufm_res As UFM_STATUS
        ' Input finger data
        Dim Template As Byte() = New Byte(MAX_TEMPLATE_SIZE) {}
        Dim TemplateSize As Integer
        ' DB data
        Dim DBTemplate As Byte()() = Nothing
        Dim DBTemplateSize As Integer() = Nothing
        Dim DBSerial As Integer() = Nothing
        Dim DBTemplateNum As Integer
        '
        Dim MatchIndex As Integer

        ufd_res = m_Database.GetTemplateListWithSerial(DBTemplate, DBTemplateSize, DBTemplateNum, DBSerial)

        If (ufd_res <> UFD_STATUS.OK) Then
            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "VERIFICANDO HUELLA DACTILAR"
            TextBox1.Select()
            TextBox1.Focus()
            Application.DoEvents()

            UFDatabase.GetErrorString(ufd_res, m_strError)
            MsgBox("No se pudieron leer las huellas de la base de datos", MsgBoxStyle.Critical, "Aviso")
            'GUARDAR SIN HUELLA
            Diesel.Texto01 = "Se guardo sin huella porque no se pudo leer la BD"

            Guardar()


            Application.DoEvents()
            Exit Sub
        End If

        If (Not ExtractTemplate(Template, TemplateSize)) Then
            Exit Sub
        End If

        DrawCapturedImage(m_Scanner)
        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufm_res = m_Matcher.Identify(Template, TemplateSize, DBTemplate, DBTemplateSize, DBTemplateNum, 5000, MatchIndex)
        Windows.Forms.Cursor.Current = Me.Cursor
        If (ufm_res <> UFM_STATUS.OK) Then
            UFMatcher.GetErrorString(ufm_res, m_strError)
            MsgBox("No se pudo identificar: " & m_strError & ", reintente por favor", MsgBoxStyle.Critical, "Aviso")
            VerificaHuellaGuardado()
            Application.DoEvents()
            Exit Sub
        End If

        If (MatchIndex <> -1) Then
            Dim CodigoOperador As String = BuscarStrDatoBiometriaOperadores("SELECT UserID FROM fingerprints WHERE Serial=" & DBSerial(MatchIndex))
            Dim IdOperadorHuella As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM OperadoresGlobal WHERE Codigo='" & CodigoOperador & "'")

            Dim Status As String = BuscarStrDatoCitra("SELECT EstadoEmpleado FROM OperadoresGlobal WHERE IdOperador=" & IdOperadorHuella)
            If Status = "B" Then
                MsgBox("El operador fué dado de baja, reintente por favor!", MsgBoxStyle.Critical, "Aviso")
                VerificaHuellaGuardado()
                Application.DoEvents()

                Exit Sub
            End If

            Dim IdOperador As Integer = BuscarIntDatoCitra("SELECT IdOperador FROM OperadoresGlobal WHERE Nombre='" & txtOperador.Text & "' AND ESTADOEMPLEADO<>'B'")

            If IdOperador = IdOperadorHuella Then
                'GUARDA
                'IMPRIME TICKET
                'INICIALIZA
                'CAMPOS GENERALES NUEVOS
                Diesel.Texto01 = ""
                Guardar()

            Else
                If IntentosHuella = 3 Then
                    MsgBox("El operador no corresponde con el indicado en la órden de abasto despues de 3 intentos", MsgBoxStyle.Critical, "Aviso")
                    'GUARDAR SIN HUELLA
                    Diesel.Texto01 = "Se guardo sin huella porque excedio el número de intentos"
                    Guardar()

                    Application.DoEvents()
                    Exit Sub
                Else
                    IntentosHuella = IntentosHuella + 1

                    MsgBox("El operador no corresponde con el indicado en la órden de abasto", MsgBoxStyle.YesNo, "Aviso")
                    txtStatus.ForeColor = Color.Red
                    txtStatus.Text = "REINTENTANDO VERIFICACIÓN DE HUELLA DACTILAR"
                    TextBox1.Select()
                    TextBox1.Focus()
                    Application.DoEvents()
                    VerificaHuellaGuardado()
                End If


            End If
        Else
            MsgBox("La huella indicada, no ha sido registrada, reintente por favor", MsgBoxStyle.Information, "Aviso")
            VerificaHuellaGuardado()
            Application.DoEvents()
            Exit Sub
        End If
    End Sub
    Sub Guardar()
        Dim Fecha As String = Now.ToString("MM/dd/yyyy")

        Diesel.IdTanque = BuscarIntDatoCitra("SELECT IDTANQUE FROM TANQUES WHERE NOMBRE='" & txtTanque.Text & "'")
        Diesel.NoCarga = BuscarIntDatoCitra("SELECT COUNT(*) FROM DIESELTEMP WHERE IDTANQUE=" & Diesel.IdTanque & " AND CONVERT(VARCHAR,FECHA,101)='" & Fecha & "'") + 1
        Diesel.Fecha = Now()
        Dim Hora As DateTime = Now()
        Diesel.Hora = Hora
        Diesel.Cuentalitros = CDbl(txtCuentalitros.Text)
        Diesel.LitrosDisponibles = CDbl(txtLtsDisponibles.Text)
        Diesel.Kardex = 0
        Diesel.Precio = CDbl(txtPrecio.Text)
        Diesel.LitrosSurtidos = CDbl(txtSurtidos.Text)
        Diesel.IdAutobus = BuscarIntDatoCitra("SELECT IdAutobus FROM Autobuses WHERE NOECONOMICO='" & txtAutobus.Text & "' AND ESTATUS=1")
        Diesel.NoEconomico = txtAutobus.Text
        Diesel.IdRuta = BuscarIntDatoCitra("SELECT IdRuta FROM RUTAS WHERE NOMBRE='" & txtRuta.Text & "'")
        Diesel.NombreRuta = txtRuta.Text
        Diesel.Litros = CDbl(txtLtsReales.Text)
        Diesel.KilometrosTotales = CDbl(txtKmsTotales.Text)
        Diesel.KilometrosOperacion = CDbl(txtKmsTrabajados.Text)
        Diesel.KilometrosMuertos = CDbl(txtKmsMuertos.Text)
        Diesel.RendimientoStandart = CDbl(txtRndStd.Text)
        Diesel.RendimientoDia = CDbl(txtRndDia.Text)
        Diesel.RendimientoAnterior = 0
        Diesel.Subtotal = CDbl(txtSubtotal.Text)
        Diesel.IVA = CDbl(txtIVA.Text)
        Diesel.Total = CDbl(txtTOTAL.Text)
        Diesel.CodigoOperador = BuscarStrDatoCitra("SELECT CODIGO FROM OPERADORESGLOBAL WHERE NOMBRE='" & txtOperador.Text & "' AND ESTADOEMPLEADO<>'B'")
        Diesel.NombreOperador = txtOperador.Text
        Diesel.CodigoDespachador = UsuarioActivo
        Diesel.NombreDespachador = BuscarStrDatoInicial("SELECT NOMBRECOMPLETO FROM USUARIOS WHERE NOMBRE='" & Diesel.CodigoDespachador & "'")
        Diesel.Importe01 = 0
        Diesel.Importe02 = 0
        Diesel.Importe03 = 0
        Diesel.Importe04 = 0
        Diesel.Importe05 = 0
        Diesel.Texto02 = ""
        Diesel.Texto03 = ""
        Diesel.Texto04 = ""
        Diesel.Texto05 = ""


        Dim TEMP As New clsDieselTemp
        TEMP.IdTanque = Diesel.IdTanque
        TEMP.NoCarga = Diesel.NoCarga
        TEMP.Fecha = Diesel.Fecha
        TEMP.IdAutobus = Diesel.IdAutobus
        TEMP.NoEconomico = txtAutobus.Text
        TEMP.IdRuta = Diesel.IdRuta
        TEMP.NombreRuta = txtRuta.Text
        TEMP.Litros = CDbl(txtLtsReales.Text)
        TEMP.KilometrosTotales = CDbl(txtKmsTotales.Text)
        TEMP.KilometrosOperacion = CDbl(txtKmsTrabajados.Text)
        TEMP.KilometrosMuertos = CDbl(txtKmsMuertos.Text)
        TEMP.Subtotal = CDbl(txtSubtotal.Text)
        TEMP.IVA = CDbl(txtIVA.Text)
        TEMP.Total = CDbl(txtTOTAL.Text)


        Diesel.Insertar()
        TEMP.Insertar()

        If chTicket.Checked = True Then
            ImprimirTicket(True)
        End If


        ActualizarDatos(Diesel.IdAutobus, Diesel.IdTanque)


    End Sub
    Sub ActualizarDatos(ByVal IdAutobus As Integer, ByVal IdTanque As Integer)
        Dim Hora As DateTime = Now()
        Call SetSqlCitra("UPDATE Autobuses SET Texto05='" & Hora & "' WHERE IdAutobus=" & IdAutobus)
        Call SetSqlCitra("DELETE FROM STATUSCARGADIESEL WHERE IdTanque=" & IdTanque)
        Call SetSqlCitra("UPDATE TANQUES SET CUENTALITROS=" & txtCuentalitros.Text & ", LTSAPROXIMADOS=" & txtLtsDisponibles.Text & " WHERE IdTanque=" & IdTanque)

        Dim IdOrden As Integer = BuscarIntDatoCitra("SELECT IdOrden FROM OrdenDiesel WHERE IdAutobus=" & IdAutobus & " AND Status='P' OR STATUS='R'")
        Dim ORDEN As New clsOrdenDiesel
        ORDEN.LtsDesp = CDbl(txtLtsReales.Text)
        ORDEN.FechaSurtido = Now()
        ORDEN.IdOrden = IdOrden
        ORDEN.ActualizarCarga()

        txtAutobus.Clear()
        txtRuta.Clear()
        txtOperador.Clear()
        txtLitros.Clear()
        txtKmsMuertos.Clear()
        txtKmsTotales.Clear()
        txtKmsTrabajados.Clear()
        txtRndDia.Clear()
        txtRndDif.Clear()
        txtRndStd.Clear()
        txtSubtotal.Clear()
        txtIVA.Clear()
        txtTOTAL.Clear()

        i = Bloquear(1)

        txtStatus.ForeColor = Color.Green
        txtStatus.Text = "PRESIONE EL BOTON 'INICIAR' PARA COMENZAR"
        btnSalir.Enabled = True
        btnIniciar_2.Enabled = True
        TextBox1.Select()
        TextBox1.Focus()
        Application.DoEvents()


    End Sub

    Sub GereraTotal()
        txtSubtotal.Text = Format(CDbl(txtLtsReales.Text) * CDbl(txtPrecio.Text), "N2")
        txtIVA.Text = Format(CDbl(txtSubtotal.Text) * 0.16, "N2")
        txtTOTAL.Text = Format(CDbl(txtSubtotal.Text) + CDbl(txtIVA.Text), "N2")

        txtLtsDisponibles.Text = CDbl(txtLtsDisponibles.Text) - CDbl(txtLtsReales.Text)
        txtSurtidos.Text = CDbl(txtSurtidos.Text) + CDbl(txtLtsReales.Text)
        txtCuentalitros.Text = CDbl(txtCuentalitros.Text) + CDbl(txtLtsReales.Text)

    End Sub
    Sub KilometrosOptocontrol()
        Dim cnConn As New SqlConnection
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader
        Dim strSql As String

        Dim UltimaFecha As String = BuscarStrDatoCitra("SELECT TEXTO05 FROM AUTOBUSES WHERE NOECONOMICO='" & txtAutobus.Text & "' AND ESTATUS=1")
        Dim FechaInicial As String
        Dim HoraInicial As Date
        Dim FechaInicialDate As Date

        If UltimaFecha = "" Then
            FechaInicial = Now.AddDays(-1).ToString("MM/dd/yyyy")
            HoraInicial = Now.AddDays(-1)
            FechaInicialDate = Now.AddDays(-1)
        Else
            FechaInicial = CDate(UltimaFecha).ToString("MM/dd/yyyy")
            HoraInicial = CDate(UltimaFecha)
            FechaInicialDate = CDate(UltimaFecha)
        End If

        Dim FechaFinal As String = Now.ToString("MM/dd/yyyy")
        Dim ID_VEHICULO As String = BuscarStrDatoCitra("SELECT TEXTO02 FROM AUTOBUSES WHERE NOECONOMICO='" & txtAutobus.Text & "' AND ESTATUS=1")

        Try
            cnConn.ConnectionString = OptocontrolConnection
            strSql = "SELECT FECHA_HORA,DISTANCIA FROM REGISTRO R INNER JOIN VEHICULO V ON R.ID_VEHICULO=V.ID_VEHICULO WHERE CONVERT(VARCHAR,FECHA,101)>='" & FechaInicial & "' AND CONVERT(VARCHAR,FECHA,101)<='" & FechaFinal & "' AND R.ID_VEHICULO='" & ID_VEHICULO & "' ORDER BY COD_VEHICULO"

            cmdBuscar.Connection = cnConn
            cmdBuscar.CommandText = strSql

            cnConn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            txtStatus.ForeColor = Color.Green
            txtStatus.Text = "BUSCANDO KILOMETROS, POR FAVOR ESPERE..."
            TextBox1.Select()
            TextBox1.Focus()
            Application.DoEvents()

            Dim Primero As Boolean = True

            Dim SUBIDAS As Integer = 0
            Dim BAJADAS As Integer = 0
            Dim Verifica As Integer = 0
            Dim Abordo As Integer = 0
            Dim HoraInt As Integer = 0
            Dim Minutos As Integer = 0
            Dim Hora As Date
            Dim Rango As String = ""
            Dim Fecha As Date

            Dim Trabajados As Double = 0
            Dim Kilometros As Double = 0

            Do While rdBuscar.Read()
                Hora = rdBuscar("FECHA_HORA")
                Fecha = rdBuscar("FECHA_HORA")

                If FechaInicialDate.ToShortDateString = Fecha.ToShortDateString Then
                    'VERIFICA HORA
                    If Hora.ToShortTimeString >= HoraInicial.ToShortTimeString Then

                        Kilometros = Kilometros + rdBuscar("DISTANCIA")
                    End If
                Else
                    Kilometros = Kilometros + rdBuscar("DISTANCIA")
                End If

            Loop

            If Kilometros = 0 Then
                'QUE TRATAMIENTO SE LES DARA SI NO TIENEN KILOMETROS EN OPTO?
                'ESTO ES TEMPORAL
                Kilometros = 100
                Trabajados = KilometrosTrabajadosAutobus(txtAutobus.Text, FechaInicial, FechaFinal, HoraInicial, FechaInicialDate)
                txtKmsTotales.Text = Format(Kilometros, "N2")
                txtKmsTrabajados.Text = Format(Trabajados, "N2")
                txtKmsMuertos.Text = Format(Kilometros - Trabajados, "N2")
                txtRndStd.Text = Format(BuscarDblDatoCitra("SELECT Importe02 FROM AUTOBUSES WHERE NOECONOMICO='" & txtAutobus.Text & "' AND ESTATUS=1"), "N2")
                txtRndDia.Text = Format(Kilometros / CDbl(txtLtsReales.Text), "N2")
                Dim DiferenciaRnd As Double = CDbl(txtRndDia.Text) - (txtRndStd.Text)
                If DiferenciaRnd < 0 Then
                    txtRndDif.BackColor = Color.Red
                ElseIf DiferenciaRnd > 0 Then
                    txtRndDif.BackColor = Color.Green
                End If
                txtRndDif.Text = Format(DiferenciaRnd, "N2")
                Application.DoEvents()

            Else
                Trabajados = KilometrosTrabajadosAutobus(txtAutobus.Text, FechaInicial, FechaFinal, HoraInicial, FechaInicialDate)
                txtKmsTotales.Text = Format(Kilometros, "N2")
                txtKmsTrabajados.Text = Format(Trabajados, "N2")
                txtKmsMuertos.Text = Format(Kilometros - Trabajados, "N2")
                txtRndStd.Text = Format(BuscarDblDatoCitra("SELECT Importe02 FROM AUTOBUSES WHERE NOECONOMICO='" & txtAutobus.Text & "' AND ESTATUS=1"), "N2")
                txtRndDia.Text = Format(Kilometros / CDbl(txtLtsReales.Text), "N2")
                Dim DiferenciaRnd As Double = CDbl(txtRndDia.Text) - (txtRndStd.Text)
                If DiferenciaRnd < 0 Then
                    txtRndDif.BackColor = Color.Red
                ElseIf DiferenciaRnd > 0 Then
                    txtRndDif.BackColor = Color.Green
                End If
                txtRndDif.Text = Format(DiferenciaRnd, "N2")
                Application.DoEvents()
            End If

        Catch ex As Exception
            'MsgBox(ex.Message, MsgBoxStyle.Critical, "Aviso")

        Finally
            If cnConn.State = System.Data.ConnectionState.Open Then
                cnConn.Close()
            End If

        End Try



    End Sub
    Function KilometrosTrabajadosAutobus(ByVal ID_VEHICULO As String, ByVal FECHAINICIAL As String, ByVal FECHAFINAL As String, ByVal HORAINICIAL As Date, ByVal FECHAINICIALDATE As Date)
        Dim cnConn As New SqlConnection
        Dim cmdBuscar As New SqlCommand
        Dim rdBuscar As SqlDataReader
        Dim strSql As String
        Dim Kilometros As Double = 0

        'MsgBox(COD_VEHICULO & ", " & FECHAINICIAL & ", " & FECHAFINAL & ", " & HORAINICIAL)


        Try
            cnConn.ConnectionString = OptocontrolConnection
            strSql = "SELECT FECHA_HORA_INICIO,KILOMETROS FROM HISTORICO_RECAUDACION R INNER JOIN VEHICULO V ON R.ID_VEHICULO=V.ID_VEHICULO WHERE R.ID_VAHICULO='" & ID_VEHICULO & "' AND CONVERT(VARCHAR,FECHA_HORA_INICIO,101)>='" & FECHAINICIAL & "' AND CONVERT(VARCHAR,FECHA_HORA_FIN,101)<='" & FECHAFINAL & "'"

            cmdBuscar.Connection = cnConn
            cmdBuscar.CommandText = strSql

            cnConn.Open()
            rdBuscar = cmdBuscar.ExecuteReader

            Dim Primero As Boolean = True

            Dim SUBIDAS As Integer = 0
            Dim BAJADAS As Integer = 0
            Dim Verifica As Integer = 0
            Dim Abordo As Integer = 0
            Dim HoraInt As Integer = 0
            Dim Minutos As Integer = 0
            Dim Hora As Date
            Dim Rango As String = ""
            Dim Fecha As Date
            Dim RNG As Integer = 5



            Do While rdBuscar.Read()
                Fecha = rdBuscar("FECHA_HORA_INICIO")
                Hora = rdBuscar("FECHA_HORA_INICIO")
                If FECHAINICIALDATE.ToShortDateString = Fecha.ToShortDateString Then
                    'VERIFICA HORA
                    If Hora.ToShortTimeString >= HORAINICIAL.ToShortTimeString Then
                        Kilometros = Kilometros + rdBuscar("KILOMETROS")
                    End If
                Else
                    Kilometros = Kilometros + rdBuscar("KILOMETROS")
                End If
            Loop
        Catch ex As Exception
            'MsgBox(ex.Message, MsgBoxStyle.Critical, "Aviso")

        Finally
            If cnConn.State = System.Data.ConnectionState.Open Then
                cnConn.Close()
            End If



        End Try

        Return Kilometros

    End Function

    Private Sub btnIniciar_2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIniciar_2.Click
        Dim IdTanque As Integer = BuscarIntDatoCitra("SELECT IdTanque FROM Tanques WHERE Nombre='" & txtTanque.Text & "'")
        Dim Status As Integer = BuscarIntDatoCitra("SELECT IdStatus FROM StatusCorteDiesel WHERE IdTanque=" & IdTanque)
        If Status > 0 Then
            MsgBox("Por el momento no puede abastecer diesel ya que el tanque esta en proceso de revisión", MsgBoxStyle.Information, "Aviso")
        Else
            btnIniciar_2.Enabled = False
            TextBox1.Select()
            TextBox1.Focus()
            Application.DoEvents()

            LeerRFID(IdTanque)
        End If
    End Sub

    Private Sub pbTicket_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pbTicket.Click
        If chTicket.Checked = True Then
            chTicket.Checked = False
            pbTicket.BackgroundImage = Image.FromFile(Application.StartupPath & "\Check0.png")
            lblTicket.Text = "Sin Ticket"
        Else
            chTicket.Checked = True
            pbTicket.BackgroundImage = Image.FromFile(Application.StartupPath & "\Check1.png")
            lblTicket.Text = "Ticket"
        End If
    End Sub
    Private Sub ImprimirTicket(ByVal esPreview As Boolean)

        If prtSettingsBoletos Is Nothing Then
            prtSettingsBoletos = New PrinterSettings
        End If

        If prtDoc3Boletos Is Nothing Then
            prtDoc3Boletos = New System.Drawing.Printing.PrintDocument
            AddHandler prtDoc3Boletos.PrintPage, AddressOf prt_PapeletaBoletosTiket
        End If

        ' la línea actual
        'lineaActual = 0

        ' la configuración a usar en la impresión
        prtDoc3Boletos.PrinterSettings = prtSettingsBoletos

        If esPreview Then
            Dim prtPrev As New PrintPreviewDialog
            prtPrev.Document = prtDoc3Boletos

            prtPrev.Text = "Previsualizar documento"
            prtPrev.ShowDialog()
        Else
            prtDoc3Boletos.Print()
        End If
    End Sub
    Private Sub prt_PapeletaBoletosTiket(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        ' Este evento se produce cada vez que se va a imprimir una página
        Dim lineHeight As Single
        Dim yPos As Single = e.MarginBounds.Top
        Dim leftMargin As Single = e.MarginBounds.Left
        Dim printFont As System.Drawing.Font
        Dim sb As System.Text.StringBuilder

        ' Asignar el tipo de letra
        printFont = New System.Drawing.Font("Arial", 10, FontStyle.Bold)
        lineHeight = printFont.GetHeight(e.Graphics)
        '
        'ENCABEZADO
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Consorcio Optra")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 100, 5)

        printFont = New System.Drawing.Font("Arial", 8)
        yPos += lineHeight
        sb = New System.Text.StringBuilder

        Dim Empresa As String = BuscarStrDatoCitra("SELECT CVALORCL01 FROM MGW10020 C INNER JOIN MGW10002 A ON C.CIDVALOR01=A.CIDVALOR02 WHERE A.cCODIGOC01='" & txtRuta.Text.Trim & "'")
        sb.AppendFormat("{0} ", Empresa)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 20)

        printFont = New System.Drawing.Font("Arial", 8)
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Ticket de Diesel")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 105, 35)

        printFont = New System.Drawing.Font("Arial", 8)
        'Imprime el Operador
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Operador: " & txtOperador.Text.Trim)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 60)


        'Imprime el autobus
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Autobus: " & txtAutobus.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 75)

        'Imprime la Ruta
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtRuta.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 90)

        'Imprime la fecha
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        Dim Fecha As DateTime = Now()

        sb.AppendFormat("{0} ", "Fecha: " & Fecha)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 105)

        'Imprime las vueltas
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Kilometros: " & txtKmsTotales.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 120)

        'Imprime el folio
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Folio: " & Diesel.IdDiesel)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 150)

        'Imprime encabezado boletos


        'Imprime linea 1
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 180)

        'Imprime encabezado boletos 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "            Lts Orden                     LtsSurtidos ")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 190)

        'Imprime linea 2
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 190)

        'Imprime serie
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtLitros.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 55, 205)

        'Imprime Inicial
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", txtLtsReales.Text)
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 200, 205)

        'Imprime linea 1
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "____________________________________________________")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 10, 220)

       
        'Imprime serie

        Dim total As Double
        Dim decimales As String
        Dim numeros As Integer
        Dim distancia As Integer
        total = txtTotal.Text
        numeros = Len(total)
        If total > 0 And total < 10 Then
            distancia = 3
        ElseIf total > 9 And total < 100 Then
            distancia = 4
        ElseIf total > 99 And total < 1000 Then
            distancia = 5
        ElseIf total > 999 And total < 10000 Then
            distancia = 6
        ElseIf total > 9999 And total < 100000 Then
            distancia = 7
        ElseIf total > 99999 And total > 1000000 Then
            distancia = 8
        ElseIf total > 999999 And total > 10000000 Then
            distancia = 9
        End If
        'decimales = Mid((txtTotal.Text), distancia, 2)
        'Dim Cantidad As String = Num2Text(Int(total)) & " PESOS " & decimales & "/100 M.N"

        'Imprime total a liquidar
        yPos += lineHeight
        sb = New System.Text.StringBuilder
        sb.AppendFormat("{0} ", "Total: $" & txtTOTAL.Text & ".00")
        e.Graphics.DrawString(sb.ToString, printFont, Brushes.Black, 95, 295)

    End Sub
    Public Function Num2Text(ByVal value As Double) As String
        Select Case value
            Case 0 : Num2Text = "CERO"
            Case 1 : Num2Text = "UN"
            Case 2 : Num2Text = "DOS"
            Case 3 : Num2Text = "TRES"
            Case 4 : Num2Text = "CUATRO"
            Case 5 : Num2Text = "CINCO"
            Case 6 : Num2Text = "SEIS"
            Case 7 : Num2Text = "SIETE"
            Case 8 : Num2Text = "OCHO"
            Case 9 : Num2Text = "NUEVE"
            Case 10 : Num2Text = "DIEZ"
            Case 11 : Num2Text = "ONCE"
            Case 12 : Num2Text = "DOCE"
            Case 13 : Num2Text = "TRECE"
            Case 14 : Num2Text = "CATORCE"
            Case 15 : Num2Text = "QUINCE"
            Case Is < 20 : Num2Text = "DIECI" & Num2Text(value - 10)
            Case 20 : Num2Text = "VEINTE"
            Case Is < 30 : Num2Text = "VEINTI" & Num2Text(value - 20)
            Case 30 : Num2Text = "TREINTA"
            Case 40 : Num2Text = "CUARENTA"
            Case 50 : Num2Text = "CINCUENTA"
            Case 60 : Num2Text = "SESENTA"
            Case 70 : Num2Text = "SETENTA"
            Case 80 : Num2Text = "OCHENTA"
            Case 90 : Num2Text = "NOVENTA"
            Case Is < 100 : Num2Text = Num2Text(Int(value \ 10) * 10) & " Y " & Num2Text(value Mod 10)
            Case 100 : Num2Text = "CIEN"
            Case Is < 200 : Num2Text = "CIENTO " & Num2Text(value - 100)
            Case 200, 300, 400, 600, 800 : Num2Text = Num2Text(Int(value \ 100)) & "CIENTOS"
            Case 500 : Num2Text = "QUINIENTOS"
            Case 700 : Num2Text = "SETECIENTOS"
            Case 900 : Num2Text = "NOVECIENTOS"
            Case Is < 1000 : Num2Text = Num2Text(Int(value \ 100) * 100) & " " & Num2Text(value Mod 100)
            Case 1000 : Num2Text = "MIL"
            Case Is < 2000 : Num2Text = "MIL " & Num2Text(value Mod 1000)
            Case Is < 1000000 : Num2Text = Num2Text(Int(value \ 1000)) & " MIL"
                If value Mod 1000 Then Num2Text = Num2Text & " " & Num2Text(value Mod 1000)
            Case 1000000 : Num2Text = "UN MILLON"
            Case Is < 2000000 : Num2Text = "UN MILLON " & Num2Text(value Mod 1000000)
            Case Is < 1000000000000.0# : Num2Text = Num2Text(Int(value / 1000000)) & " MILLONES "
                If (value - Int(value / 1000000) * 1000000) Then Num2Text = Num2Text & " " & Num2Text(value - Int(value / 1000000) * 1000000)
            Case 1000000000000.0# : Num2Text = "UN BILLON"
            Case Is < 2000000000000.0# : Num2Text = "UN BILLON " & Num2Text(value - Int(value / 1000000000000.0#) * 1000000000000.0#)
            Case Else : Num2Text = Num2Text(Int(value / 1000000000000.0#)) & " BILLONES"
                If (value - Int(value / 1000000000000.0#) * 1000000000000.0#) Then Num2Text = Num2Text & " " & Num2Text(value - Int(value / 1000000000000.0#) * 1000000000000.0#)
        End Select
    End Function
End Class